import Vapor

struct CountryController: RouteCollection {

  func boot(routes: RoutesBuilder) throws {
    let routes = routes.grouped("api", "country")
    routes.get(use: getAllHandler)
    routes.post(use: createHandler)
    routes.get(":countryID", use: getHandler)
    routes.put(use: updateHandler)
    routes.delete(":countryID", use: deleteHandler)
  }

    func getAllHandler(_ req: Request) throws -> EventLoopFuture<[Country]> {
        Country.query(on: req.db).all()
    }
    
    func createHandler(_ req: Request) throws -> EventLoopFuture<Country> {
      let data = try req.content.decode(Country.self)
      return data.save(on: req.db).map { data }
    }

    func getHandler(_ req: Request) throws -> EventLoopFuture<Country> {
        Country.find(req.parameters.get("countryID"), on: req.db)
      .unwrap(or: Abort(.notFound))
    }

    func updateHandler(_ req: Request) throws -> EventLoopFuture<Country> {
      let updateData = try req.content.decode(Country.self)
        return Country.find(updateData.id, on: req.db)
        .unwrap(or: Abort(.notFound)).flatMap { country in
            country.name = updateData.name
            country.iso = updateData.iso
            country.centerLatitude = updateData.centerLatitude
            country.centerLongitude = updateData.centerLongitude
          return country.save(on: req.db).map {
            country
          }
      }
    }

    func deleteHandler(_ req: Request)
      throws -> EventLoopFuture<HTTPStatus> {
        Country.find(req.parameters.get("countryID"), on: req.db)
        .unwrap(or: Abort(.notFound))
        .flatMap { country in
            country.delete(on: req.db)
            .transform(to: .noContent)
      }
    }
}

